﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using cacrb.Models;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using Webdiyer.WebControls.Mvc;

namespace cacrb.Controllers
{
    public class DefaultController : Controller
    {
        //
        // GET: /Default/

        public static readonly string ChannelFrom = WebConfigurationManager.AppSettings["channelFrom"];//渠道
        public static readonly string IsPost = WebConfigurationManager.AppSettings["IsPost"];//是否提交 
        //表单页面
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 移动端页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Mobile()
        {
            return View();
        }

        //List页面
        public ActionResult List()
        {
            return View();
        }

        #region 下拉车型、经销商
        public JsonResult GetDealer(int aid, string groupId, string provinceId, string cityId, string town)
        {
            var db = new cacrmEntities();

            var data = db.getdealerinfo(groupId, provinceId, cityId, town, aid).ToList().Select(s => new { s.dealerId, s.dealerName });

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetMaterial(int aid)
        {

            var db = new cacrmEntities();

            var data = db.getmaterial(aid).ToList().Select(s => new { s.groupId, s.groupName });

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 下拉省市区
        public JsonResult GetProvince()
        {
            var db = new cacrmEntities();

            //省
            var data = (from s in db.tb_tmregion
                        where s.regionType == "10541002" && s.status == "10011001"
                        select new { id = s.regionId, text = s.regionName }).Distinct();

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetCityByProvince(string id, int aid)
        {
            var db = new cacrmEntities();
            string type = db.sys_Setting.FirstOrDefault(s => s.aid == aid).type;
            //市
            var data = (from s in db.tb_tmregion
                        where s.regionType == "10541003" && s.parentCode == id && s.status == "10011001" && s.type == type
                        select new { id = s.regionId, text = s.regionName }).Distinct();

            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetTownByCity(string id, int aid)//,string notinstr
        {
            string[] regs = new[] { "南川区", "大渡口区", "沙坪坝区", "江北区", "綦江区", "铜梁区", "城口县", "丰都县", "垫江县", "武隆县", "忠县",
                "奉节县", "巫山县", "巫溪县", "石柱土家族自治县", "酉阳土家族苗族自治县", "彭水苗族土家族自治县" };
            if (aid > 100)
                regs = new[] { "测试" };

            //string[] regs = notinstr.Split(',');

            var db = new cacrmEntities();

            string type = db.sys_Setting.FirstOrDefault(s => s.aid == aid).type;
            //区
            var data = (from s in db.tb_tmregion
                        where s.regionType == "10541004" && s.parentCode == id && s.status == "10011001" && s.type == type
                        && !regs.Contains(s.regionName)
                        select new { id = s.regionId, text = s.regionName }).Distinct();

            return Json(data, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 保存DB
        public JsonResult SaveForm(int aid, string phone, string name, string carmodel, string dealer, string provinceId, string cityId, string town, string gender)
        {
            ResultInfo result = new ResultInfo();
            try
            {
                var db = new cacrmEntities();

                var exit = db.Base_User.FirstOrDefault(s => s.Phone == phone && s.aid == aid);
                if (exit == null)
                {

                    Base_User model = new Base_User
                    {
                        CreateTime = DateTime.Now,
                        Phone = phone,
                        Name = name,
                        ID_Group = carmodel,
                        ID_dealer = decimal.Parse(dealer),
                        Gender = gender,
                        ID_Province = provinceId,
                        ID_City = cityId,
                        ID_Town = town
                    };
                    db.Base_User.Add(model);

                    var set = db.sys_Setting.FirstOrDefault(s => s.aid == aid);
                    string param = "error";
                    string restr = "error";
                    if (set != null)
                    {
                        string url = set.url + "?op=" + set.op + "&aid=" + set.aid;
                        //"http://www.changan.com.cn/api.php?op=try&aid=42";
                        param = GetStr(name, phone, dealer, carmodel, provinceId, cityId, town);
                        restr = IsPost == "1" ? HttpPost(url, param) : "没有提交";
                        model.ID_Set = set.ID;
                    }
                    model.PostParam = param;
                    model.SendResult = restr;
                    model.SendTime = DateTime.Now;
                    model.aid = aid;


                    if (db.SaveChanges() < 0)
                    {
                        result.IsSucceed = false;
                        result.Message = "保存失败";
                    }
                    else
                    {
                        result.IsSucceed = true;
                        result.Message = "提交成功"; //re.Html;
                    }
                }
                else
                {
                    result.IsSucceed = false;
                    result.Message = "您已提交过信息了哦";

                }
            }
            catch (Exception ex)
            {
                result.Message = "出错了诶"; //ex.StackTrace + ex.Message;
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Post官网
        public string GetStr(string name, string phone, string dealer, string carmodel, string province, string city, string town)
        {
            var db = new cacrmEntities();
            var dealerInfo = db.tb_tmdealerinfo.FirstOrDefault(s => s.dealerId == dealer);
            var materialInfo = db.tb_tmvhclmaterialgroup.FirstOrDefault(s => s.groupId == carmodel);
            var provinceInfo = db.tb_tmregion.FirstOrDefault(s => s.regionId == province);
            var cityInfo = db.tb_tmregion.FirstOrDefault(s => s.regionId == city);
            var townInfo = db.tb_tmregion.FirstOrDefault(s => s.regionId == town);
            var brand = "";
            switch (dealerInfo.dataType)
            {
                case "乘用车":
                    brand = "1";
                    break;
                case "商用车":
                    brand = "2";
                    break;
                case "轻型车":
                    brand = "3";
                    break;
            }

            //string url = "http://www.changan.com.cn/api.php?op=try&aid=42";
            string str = //"op=" + HttpUtility.UrlEncode("try") +
                //"&aid=" + HttpUtility.UrlEncode("42") +
                "trail_channel_from=" + HttpUtility.UrlEncode(ChannelFrom) +
                "&name=" + HttpUtility.UrlEncode(name) +
                "&mobile=" + HttpUtility.UrlEncode(phone) +
                "&dealer_brand=" + HttpUtility.UrlEncode(brand) +
                "&car_series=" + HttpUtility.UrlEncode(materialInfo.groupCode) +
                "&car_series_name=" + HttpUtility.UrlEncode(materialInfo.groupName) +
                "&region_id_1=" + HttpUtility.UrlEncode(provinceInfo.regionCode) +
                "&region_id_1_name=" + HttpUtility.UrlEncode(provinceInfo.regionName) +
                "&region_id_2=" + HttpUtility.UrlEncode(cityInfo.regionCode) +
                "&region_id_2_name=" + HttpUtility.UrlEncode(cityInfo.regionName);

            if (townInfo != null)
            {
                str += "&region_id_3=" + HttpUtility.UrlEncode(townInfo.regionCode) +
                    "&region_id_3_name=" + HttpUtility.UrlEncode(townInfo.regionName);
            }

            str += "&dealer_code=" + HttpUtility.UrlEncode(dealerInfo.dealerCode) +
         "&dealer_id=" + HttpUtility.UrlEncode(dealerInfo.dealerId) +
         "&dealer_code_name=" + HttpUtility.UrlEncode(dealerInfo.dealerName); //+

            //"&visit_time=" + HttpUtility.UrlEncode("2016-04-22 18:18") +
            //"&order_time=" + HttpUtility.UrlEncode("2016-04-22 18:18");
            return str;
            //return HttpPost(url, str); 

        }


        /// <summary>
        /// POST请求与获取结果
        /// </summary>
        public static string HttpPost(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
            writer.Write(postDataStr);
            writer.Flush();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            if (encoding == null || encoding.Length < 1)
            {
                encoding = "UTF-8"; //默认编码
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = reader.ReadToEnd();
            return retString;
        }

        #endregion

        #region 获取List数据
        public string GetList(string datefrom, string dateto, string carmodel, string dealer)
        {
            int page = Request.Form["page"] == null ? 0 : Int32.Parse(Request.Form["page"].ToString());
            int rows = Request.Form["rows"] == null ? 10 : Int32.Parse(Request.Form["rows"].ToString());
            string sort = Request.Form["sort"] == null ? "" : Request.Form["sort"].ToString();
            string order = Request.Form["order"] == null ? "" : Request.Form["order"].ToString();

            var db = new cacrmEntities();
            StringBuilder sb = new StringBuilder();


            //var data =  db.Base_User.Where(s=>s.Phone =="1");
            datefrom = string.IsNullOrEmpty(datefrom) ? "" : DateTime.Parse(datefrom).AddDays(-1).ToString("yyyy-MM-dd");
            dateto = string.IsNullOrEmpty(dateto) ? "" : DateTime.Parse(dateto).AddDays(1).ToString("yyyy-MM-dd");
            var data = db.getlist(dealer, carmodel, datefrom, dateto).ToList();
            sb.Append("{\"total\":" + data.Count() + ", ");
            sb.Append("\"rows\":" + JsonConvert.SerializeObject(data.AsQueryable<view_User>().ToPagedList(page, rows).ToList()));
            sb.Append("}");

            return sb.ToString();
        }
        #endregion

        #region 获取省市JSON

        public string GetProvinceCityJson()
        {
            var db = new cacrmEntities();
            string json = "[";
            //省
            var data = (from s in db.tb_tmregion
                        where s.regionType == "10541002" && s.status == "10011001"
                        select new { id = s.regionId, text = s.regionName }).Distinct();
            foreach (var item in data)
            {
                json += "{\"id\":\"" + item.id + "\", \"text\":\"" + item.text + "\",\"sub\":[";
                //市
                var city = (from s in db.tb_tmregion
                            where s.regionType == "10541003" && s.parentCode == item.id && s.status == "10011001"
                            select new { id = s.regionId, text = s.regionName }).Distinct();
                string citystr = "";
                foreach (var i in city)
                {
                    citystr += "{\"id\":\"" + i.id + "\", \"text\":\"" + i.text + "\"},";
                }
                citystr = citystr.TrimEnd(',');
                json += citystr;
                json += " ]},";

            }
            json = json.TrimEnd(',');
            json += "]";
            return json;
        }

        //直辖市 市  市
        public string GetProvinceCityJson2()
        {
            var db = new cacrmEntities();
            string json = "[";
            //省
            var data = (from s in db.tb_tmregion
                        where //s.regionType == "10541003" && 
                        s.status == "10011001" &&
                         (s.regionId == "1000000034" || s.regionId == "1000000035" || s.regionId == "1000000105" || s.regionId == "1000000262")
                         && s.type == "轿车"
                        select new { id = s.regionId, text = s.regionName }).Distinct();
            foreach (var item in data)
            {
                json += "{\"id\":\"" + item.id + "\", \"text\":\"" + item.text + "\",\"sub\":[";
                //市
                var city = (from s in db.tb_tmregion//10541003
                            where s.regionType == "10541004" && s.parentCode == item.id && s.status == "10011001"
                             && s.type == "轿车"
                            select new { id = s.regionId, text = s.regionName }).Distinct();
                string citystr = "";
                foreach (var i in city)
                {
                    citystr += "{\"id\":\"" + i.id + "\", \"text\":\"" + i.text + "\"},";
                }
                citystr = citystr.TrimEnd(',');
                json += citystr;
                json += " ]},";

            }
            json = json.TrimEnd(',');
            json += "]";
            return json;
        }
        #endregion

    }
}
